import React, { Component } from 'react'
//1. 引入store,获取redux中保存的状态
import store from '../../redux/store'
//2.引入action 用于创建action对象
import {
  incrementAction,
  decrementAction,
  incrementActionAsync,
} from '../../redux/count_action'
export default class Count extends Component {
  state = {
    count: 'qqqjh',
  }
  //组件挂载完成 监听数据的变化
  componentDidMount() {
    //监听数据的变化 只要有变化就调用render 渲染页面
    store.subscribe(() => {
      //只要有变化就调用render 渲染页面
      this.setState({})
    })
  }
  //加法
  increment = () => {
    const { value } = this.selectNum
    //通知redux做加法的运算,增加value
    store.dispatch(incrementAction(value * 1))
  }
  //减法
  decrement = () => {
    const { value } = this.selectNum
    //通知redux做减法的运算,减少value
    store.dispatch(decrementAction(value * 1))
  }
  //和为奇数的时候再加
  incrementOdd = () => {
    const { value } = this.selectNum
    const count = store.getState()
    if (count % 2 !== 0) {
      //通知redux做加法的运算,增加value
      store.dispatch(incrementAction(value * 1))
      // store.dispatch({
      //   type: 'INCREMENT',
      //   data: value * 1,
      // })
    }
  }
  //异步的时候加
  incrementAsync = () => {
    const { value } = this.selectNum
    //const count = store.getState()
    // setTimeout(() => {
    store.dispatch(incrementActionAsync(value * 1), 5000)
    // }, 1000)
  }
  render() {
    return (
      <div>
        {/* store.getState() 获取初始状态 */}
        <h3>当前的和为:{store.getState()}</h3>
        {/* 受控表单 用回掉函数获取数值 */}
        <select
          ref={(c) => {
            this.selectNum = c
          }}>
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3">3</option>
        </select>
        <button onClick={this.increment}>+</button>
        <button onClick={this.decrement}>-</button>
        <button onClick={this.incrementOdd}>当前和为奇数再加</button>
        <button onClick={this.incrementAsync}>异步加</button>
      </div>
    )
  }
}
